package com.lx.boot.db;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lx.annotation.Note;
import com.lx.boot.OS;
import com.lx.boot.db.domain.BaseEntity;
import com.lx.constant.DefaultBaseConstant.Enabled;
import com.lx.entity.UserInfo;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;


@Note("自动填充新增/更新人及时间信息")
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject != null && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                Date current = baseEntity.getAddTime() != null ? baseEntity.getAddTime() : new Date();
                baseEntity.setAddTime(current);
                baseEntity.setUpdateTime(current);
                UserInfo userInfo = OS.getUserInfo();
                String userId = baseEntity.getAddUser() != null ? baseEntity.getAddUser() : OS.getUserId();
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setAddUser(userId);
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdateUser(userId);
                baseEntity.setIsEnabled(baseEntity.getIsEnabled() != null ? baseEntity.getIsEnabled() : Enabled.YES);
//                baseEntity.setAddDept(baseEntity.getAddDept() != null ? baseEntity.getAddDept() : userInfo.getDeptId());
            }
        } catch (Exception e) {
            throw new RuntimeException("自动注入异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject != null && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                baseEntity.setUpdateTime( new Date());
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdateUser(OS.getUserId());
            }
        } catch (Exception e) {
            throw new RuntimeException("自动注入异常 => " + e.getMessage());
        }
    }


}
